//
//  URLComponents+Ex.swift
//  
//
//  Created by tank on 2021/11/17.
//

import Foundation

extension URLComponents: ExtensionCompatible { }

public extension Extension where Base == URLComponents {
    static func create(string: String) -> URLComponents? {
        return URLComponents(string: string.ex.isUrlEncoded ? string : (string.ex.encodeURI() ?? string))
    }
    
    func getQueryItem(key: String) -> String? {
        return base.queryItems?.first(where: {
            $0.name == key
        })?.value
    }

    func getQueryItems(keys: [String]? = nil) -> [String: String]? {
        return base.queryItems?.reduce([String: String]()) { partialResult, queryItem in
            guard keys == nil || keys?.contains(queryItem.name) == true else {
                return partialResult
            }

            var result = partialResult
            result[queryItem.name] = queryItem.value ?? ""
            return result
        }
    }
}
